import { useState, useEffect } from 'react'
import { useParams, useNavigate } from 'react-router-dom'
import apiService from '../utils/api.js'
import '../styles/pages.css'
import '../styles/playlist-detail.css' // 复用歌单详情页的样式

// 日期格式化函数
const formatDate = (dateString) => {
  try {
    const date = new Date(dateString)
    if (isNaN(date.getTime())) {
      return '未知日期'
    }
    return date.toLocaleDateString('zh-CN', {
      year: 'numeric',
      month: 'long',
      day: 'numeric'
    })
  } catch (error) {
    return '未知日期'
  }
}

function AlbumDetail({ playSong }) {
  const { id } = useParams() // 获取路由参数中的专辑ID
  const navigate = useNavigate()
  const [album, setAlbum] = useState(null)
  const [songs, setSongs] = useState([])
  const [loading, setLoading] = useState(true)
  const [error, setError] = useState('')

  // 获取专辑详情
  const fetchAlbumDetail = async () => {
    setLoading(true)
    setError('')
    try {
      // 调用API获取专辑详情
      const albumData = await apiService.getAlbumDetail(id)
      if (albumData) {
        const { songs = [], ...albumInfo } = albumData
        setAlbum(albumInfo)
        setSongs(songs)
      } else {
        // 如果API调用失败，使用模拟数据
        const mockData = getMockAlbumDetail(id)
        setAlbum(mockData)
        setSongs(mockData.songs)
      }
    } catch (err) {
      console.error('获取专辑详情失败:', err)
      setError(err.message || '获取专辑详情失败，请稍后再试')
    } finally {
      setLoading(false)
    }
  }

  // 生成模拟专辑详情数据
  const getMockAlbumDetail = (albumId) => {
    // 基础专辑数据
    const albumBase = {
      id: parseInt(albumId),
      name: '',
      artist: '',
      artistId: 1,
      cover: '',
      releaseDate: '',
      description: '',
      songs: []
    }

    // 根据ID返回不同的专辑数据
    const albumDataMap = {
      1: {
        ...albumBase,
        id: 1,
        name: '叶惠美',
        artist: '周杰伦',
        artistId: 1,
        cover: 'https://via.placeholder.com/300?text=叶惠美',
        releaseDate: '2003-07-31',
        description: '《叶惠美》是周杰伦的第四张专辑，由周杰伦担任制作人。专辑的名字来源于周杰伦的母亲叶惠美。专辑中收录了周杰伦创作的11首歌曲。',
        songs: [
          { id: 1, title: '晴天', artist: '周杰伦', album: '叶惠美', cover: 'https://via.placeholder.com/300', audio: '' },
          { id: 5, title: '以父之名', artist: '周杰伦', album: '叶惠美', cover: 'https://via.placeholder.com/300', audio: '' },
          { id: 20, title: '东风破', artist: '周杰伦', album: '叶惠美', cover: 'https://via.placeholder.com/300', audio: '' },
          { id: 21, title: '你听得到', artist: '周杰伦', album: '叶惠美', cover: 'https://via.placeholder.com/300', audio: '' },
          { id: 22, title: '同一种调调', artist: '周杰伦', album: '叶惠美', cover: 'https://via.placeholder.com/300', audio: '' }
        ]
      },
      2: {
        ...albumBase,
        id: 2,
        name: '七里香',
        artist: '周杰伦',
        artistId: 1,
        cover: 'https://via.placeholder.com/300?text=七里香',
        releaseDate: '2004-08-03',
        description: '《七里香》是周杰伦的第五张专辑，由周杰伦担任制作人。专辑中收录了周杰伦创作的10首歌曲。',
        songs: [
          { id: 2, title: '七里香', artist: '周杰伦', album: '七里香', cover: 'https://via.placeholder.com/300', audio: '' },
          { id: 23, title: '借口', artist: '周杰伦', album: '七里香', cover: 'https://via.placeholder.com/300', audio: '' },
          { id: 24, title: '搁浅', artist: '周杰伦', album: '七里香', cover: 'https://via.placeholder.com/300', audio: '' },
          { id: 25, title: '园游会', artist: '周杰伦', album: '七里香', cover: 'https://via.placeholder.com/300', audio: '' },
          { id: 26, title: '我的地盘', artist: '周杰伦', album: '七里香', cover: 'https://via.placeholder.com/300', audio: '' }
        ]
      },
      6: {
        ...albumBase,
        id: 6,
        name: '1989',
        artist: 'Taylor Swift',
        artistId: 2,
        cover: 'https://via.placeholder.com/300?text=1989',
        releaseDate: '2014-10-27',
        description: '《1989》是泰勒·斯威夫特的第五张录音室专辑，专辑名来源于她的出生年份。这张专辑标志着她从乡村音乐向流行音乐的转型。',
        songs: [
          { id: 6, title: 'Blank Space', artist: 'Taylor Swift', album: '1989', cover: 'https://via.placeholder.com/300', audio: '' },
          { id: 7, title: 'Shake It Off', artist: 'Taylor Swift', album: '1989', cover: 'https://via.placeholder.com/300', audio: '' },
          { id: 27, title: 'Style', artist: 'Taylor Swift', album: '1989', cover: 'https://via.placeholder.com/300', audio: '' },
          { id: 28, title: 'Bad Blood', artist: 'Taylor Swift', album: '1989', cover: 'https://via.placeholder.com/300', audio: '' },
          { id: 29, title: 'Wildest Dreams', artist: 'Taylor Swift', album: '1989', cover: 'https://via.placeholder.com/300', audio: '' }
        ]
      }
    }

    // 如果找不到对应的ID，返回一个默认的专辑数据
    return albumDataMap[albumId] || {
      ...albumBase,
      id: parseInt(albumId),
      name: `专辑${albumId}`,
      artist: '未知歌手',
      artistId: 1,
      cover: `https://via.placeholder.com/300?text=专辑${albumId}`,
      releaseDate: '2023-01-01',
      description: '这是一张优秀的专辑',
      songs: [
        { id: 101, title: '歌曲1', artist: '未知歌手', album: `专辑${albumId}`, cover: 'https://via.placeholder.com/300', audio: '' },
        { id: 102, title: '歌曲2', artist: '未知歌手', album: `专辑${albumId}`, cover: 'https://via.placeholder.com/300', audio: '' }
      ]
    }
  }

  // 返回上一页
  const handleBack = () => {
    navigate(-1)
  }

  // 跳转到歌手详情页
  const handleArtistClick = (artistId) => {
    navigate(`/artist/${artistId}`)
  }

  // 处理歌曲播放
  const handlePlaySong = (song) => {
    console.log('播放歌曲:', song)
    // 使用从父组件传递的playSong函数来实际播放歌曲
    if (playSong) {
      playSong(song)
    } else {
      alert(`正在播放: ${song.title}`)
    }
  }

  // 组件加载时获取数据
  useEffect(() => {
    fetchAlbumDetail()
  }, [id])

  // 加载状态显示
  if (loading) {
    return (
      <div className="playlist-detail-page loading-container">
        <div className="loading-spinner"></div>
        <p>加载中...</p>
      </div>
    )
  }

  // 错误状态显示
  if (error) {
    return (
      <div className="playlist-detail-page error-container">
        <p>{error}</p>
        <button onClick={fetchAlbumDetail}>重试</button>
      </div>
    )
  }

  return (
    <div className="playlist-detail-page">
      {/* 返回按钮 */}
      <button className="back-button" onClick={handleBack}>
        ← 返回
      </button>

      {/* 专辑信息区域 */}
      <div className="playlist-info-section">
        <div className="playlist-cover-large">
          <img 
            src={album.coverImageUrl}
            alt={album.title}
          />
        </div>
        <div className="playlist-basic-info">
          <h1 className="playlist-name-large">{album.title}</h1>
          <div className="playlist-meta-info">
            <span 
              className="playlist-creator" 
              onClick={() => handleArtistClick(album.artistId)}
              style={{ cursor: 'pointer', textDecoration: 'underline' }}
            >
              {album.artist.name}
            </span>
            <span className="playlist-date">
              发行日期: {album.releaseDate ? formatDate(album.releaseDate) : '未知日期'}
            </span>
            <span className="playlist-song-count">
              {songs.length}首歌曲
            </span>
          </div>
          <p className="playlist-description">{album.description}</p>
        </div>
      </div>

      {/* 歌曲列表 */}
      <div className="songs-section">
        <h2 className="section-title">歌曲 ({songs.length})</h2>
        <div className="songs-list">
          {songs.map((song, index) => (
            <div key={song.id} className="song-item">
              <div className="song-rank">{index + 1}</div>
              <div className="song-info">
                <div className="song-title">{song.title}</div>
              </div>
              <div className="song-actions">
                <button className="play-btn" onClick={() => handlePlaySong(song)}>
                  播放
                </button>
              </div>
            </div>
          ))}
        </div>
      </div>
    </div>
  )
}

export default AlbumDetail